<?php

if (!isset($_SESSION['login'])) {
	header('Location: /login/?page=' . urlencode($page['full_path']) . 'orders/');
	exit;
}

if (isset($path[0]) and is_numeric($path[0])) {
	
	$order = $db->fetchRow("SELECT o.*, SUM(l.price_excl_vat) AS price_excl_vat, SUM(vat) AS vat FROM shop_orders o LEFT JOIN shop_orders_lines l ON o.id=l.order_id WHERE user_id=? AND o.id=? GROUP BY o.id ORDER BY id DESC", array($_SESSION['login']['user']['id'], $path[0]));
	$order['lines'] = $db->fetchAll("SELECT * FROM shop_orders_lines l WHERE order_id=?", $order['id']);
	foreach($order['lines'] as $j => $line) {
		$order['lines'][$j]['simpleattributes'] = $db->fetchAll("SELECT title, value FROM shop_orders_lines_simpleattributes WHERE line_id=? ORDER BY sort", $line['id']);
	}
	$order['deliveries'] = $db->fetchAll("SELECT * FROM shop_orders_deliveries WHERE order_id=? ORDER BY id", $order['id']);
	foreach($order['deliveries'] as $j => $delivery) {
		$order['deliveries'][$j]['delivery_country'] = $db->fetchOne("SELECT title FROM cms_countries WHERE id=?", $delivery['delivery_country_id']);
	}
	
	$smarty->assign('order', $order);
	
	$smarty->display('shop/order-detail.tpl.html');
	
} else {
	
	$orders = $db->fetchAll("SELECT o.*, SUM(l.price_excl_vat) AS price_excl_vat, SUM(vat) AS vat FROM shop_orders o LEFT JOIN shop_orders_lines l ON o.id=l.order_id WHERE user_id=? GROUP BY o.id ORDER BY id DESC", $_SESSION['login']['user']['id']);
	foreach($orders as $i => $order) {
		$orders[$i]['lines'] = $db->fetchAll("SELECT * FROM shop_orders_lines l WHERE order_id=?", $order['id']);
		foreach($orders[$i]['lines'] as $j => $line) {
			$orders[$i]['lines'][$j]['simpleattributes'] = $db->fetchAll("SELECT title, value FROM shop_orders_lines_simpleattributes WHERE line_id=? ORDER BY sort", $line['id']);
		}
	}
	
	$smarty->assign('orders', $orders);
	
	$smarty->display('shop/orders.tpl.html');
	
}